<?php
namespace Admin\Model;
use Think\Model;
class TagsModel extends Model {

	public function index(){
		$uinfo = UserModel::loadFromSession();
		return $uinfo;
	}

	/*增加标签操作*/
	public function add_tags( $name ){

		$uinfo = UserModel::loadFromSession();
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		if( !$uinfo )
			$r['i'] = '加载用户信息失败';
		else if( !$name )
			$r['i'] =  L('PARAM_WRONG');
		else{
			$d = array();
			$d['tag_name'] = $name;
			$d['create_time'] = date('Y-m-d H:i:s');	
			$d['creator'] =$uinfo['user_id']; 
			$addID = $this->add( $d );
			if( $addID ){
				$r['r'] = $addID ;
				$r['i'] = 'OK';
				$r['d'] = $this->where( 'tag_id='.$addID )->find();
			}else{
				$r['i'] = '保存失败';
			}
		}
		return $r;
	}

	/** 修改标签操作*/
	public function update_tag($tag_id, $tag_name){
		$r = array('r'=>0,'i'=>'server error','d'=>NULL );
		if( $tag_id && $tag_name ) {
			$dtag = null;
			$wheres = array();
			$wheres['tag_id'] = array('eq', $tag_id );
			$dtag = $this->where( $wheres )->find();
			if( $dtag ){
				$d = array();
				$d['create_time'] = date('Y-m-d H:i:s');
				$d['tag_name'] = $tag_name;
				$this->where( $wheres )->save( $d );
				$r['r'] = 1;
				$r['d'] = $this->where( $wheres )->find();
				$r['i'] = 'OK';
			}
			else
				$r['i'] = L('NO_DATA');
		} else{
			$r['i'] = L('PARAM_WRONG');
		}
		
		return $r;
	}

	/** 删除标签操作*/
	public function delete_tag( $tag_id ,$random){

		$uinfo = UserModel::loadFromSession();

		$r = array('r'=>0,'i'=>'server error','d'=>NULL );

		if ($random==7) {

			$where = array();

			$where['tag_id'] = array('eq',$tag_id);

			$del1=M()->table('customer_tag')->where($where)->delete();
			$del2=M()->table('customer_tag_list')->where($where)->delete();

		    if ( $del1 && $del2) {
				$r['r'] = 1;
				$r['i'] = 'OK';
		    }

		}else if($random==1){

			$where = array();
			$where['tag_id'] = array('eq',$tag_id);
			$del=$this->where($where)->delete();
			if($del){
				$r['r'] = 1;
	 			$r['i'] = 'OK';
			}
		}
 		return $r;
	}

	public function delete_customer($tags_id,$tag_id){

		$r = array('r'=>0,'i'=>'server error','d'=>NULL );
		if( $tags_id )
			$r['i'] = L('PARAM_WRONG');

		$wheres = array();
		$wheres['tags_id'] = array('eq', $tags_id);
		$dlist = $this->where($wheres)->delete();

		$where =array();
		$where['tag_id'] = $tag_id;
		$MTag=M('tag','customer_');
		$marr=$MTag->where($where)->select();
		$count=$marr[0]['count'];
		$count=$count-1;

		$d = array();
		$d['tag_id'] = $tag_id;
		$d['count'] = $count;
		$d['create_time'] = date('Y-m-d H:i:s');	
		$addID = $MTag->save( $d );

		if($dlist && $addID){
			$r['r'] = 1;
			$r['i'] = 'OK';
		}else{
			$r['r'] = 2;
			$r['i'] = '用户信息删除失败！';
		}
 		return $r;
	}

}